
import React,{Component} from 'react';
import {Menu,message, Button,Select ,Card,Input,Form,Col,Row,Radio,Upload,Icon,Steps} from 'antd';
import {connect} from 'react-redux';
import {getRecruit} from '../../store/action/recruit';
import {getRecruitInfor,getFileInfor,deleteFileInfor,changeInfo,getFile,getSteps,getResultFile} from '../../store/action/userHome';
import configs from '../../store/action/common/configs';
import reqwest from 'reqwest';
import {timeFormat,getTokenHeader} from '../../utils/utils'
import './UserHome.css'
const baseUrl=configs.baseUrl;
const FormItem=Form.Item;
const { Step } = Steps;
const { Option } = Select;
const { TextArea } = Input;
@connect((state)=>({
    infor:state.userHome.infor,
    resumeId:state.userHome.resumeId,
    classes:state.recruit.classes,
    fileList:state.userHome.fileList,
    stepInfor:state.userHome.stepInfor,
    resultFile:state.userHome.resultFile
    
}))
class UserHome extends Component{
    constructor(props)
    {
        super(props);
        this.state={
            currentMenu: 'mail',
            infor:{},
            classes:[],
            loadin:false,
            avatar:'',
            uploadingP: false,
            fileList:[],
            list:[],
            resumeId:0,
            id:0,
            stepInfor:[{},{},{}],
            stepLen:0,
            file1:[],
            file2:[]
        }
    }
    componentDidMount()
    {
        let _id=this.props.match.params.id;
        this.setState({
            id:parseInt(_id) 
        })
        this.props.dispatch(getRecruit({id:_id})).then(()=>{
            this.setState({
                classes:this.props.classes
            })
        })
        this.props.dispatch(getRecruitInfor({enrollId:_id})).then(()=>{
            this.setState({
                currentMenu:'mail',
                infor:this.props.infor,
                imageUrl:this.props.infor.avatar,
                resumeId:this.props.infor.id,
                current: 0,
              
            })
            this.getInforList();
        })
        
        
    }
    /**
     * 获取附件列表
     */
    getInforList=()=>{
         this.props.dispatch(getFileInfor({resumeId:parseInt(this.state.resumeId)})).then(()=>{
                this.setState({
                    list:this.props.fileList
                })
            });
    }
    /**
     * 删除附件
     */
    deleteList=(id)=>{
        this.props.dispatch(deleteFileInfor({id:id})).then(()=>{
            this.getInforList();
        });
        
    }
    /**
     * 获取成绩文件
     */
    handleClick = e => {
        if(e.key==='app')
        {
            this.props.dispatch(getSteps({enrollId:this.state.id})).then(()=>{
                let _arr=this.props.stepInfor;
                let _len=this.props.stepInfor.length;
                for(let i=1;i<_len;i++)
                {
                    this.props.dispatch(getResultFile({
                        enrollId:this.props.stepInfor[i].enrollId,
                        stage:this.props.stepInfor[i].stage
                    })).then(()=>{
                        if(i===1)
                        {
                            this.setState({
                                file1:this.props.resultFile
                            })
                        }
                        else if(i===2)
                        {
                            this.setState({
                                file2:this.props.resultFile
                            })
                        }
                    });
                }
                for(let i=0;i<3-_len;i++)
                {
                    _arr.push({});
                }
                this.setState({
                    stepInfor:_arr,
                    stepLen:_len
                })
            });
        }
        this.setState({
            currentMenu: e.key,
        });
    };
    /**
     * 下载成绩文件
     */
    getFile=(id)=>{
        this.props.dispatch(getFile({id:id}));
    }
    /**
     * 图片调用
     */
    getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }
    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('请上传jpg或png格式的照片');
        }
        const isLt2M = file.size / 100 / 1024 < 3;
        if (!isLt2M) {
            message.error('请上传小于300kb的照片!');
        }
        return isJpgOrPng && isLt2M;
    }
    handleChange = info => {
        if (info.file.status === 'uploading') {
            this.setState({
                loading: true
            });
            return;
        }
        if (info.file.status === 'done') {
            this.getBase64(info.file.originFileObj, imageUrl => {
                    if (info.file.response.code === 'SUCCESS') {
                        this.setState({
                            imageUrl:info.file.response.data.url,
                            loading: false,
                        });
                    } else {
                        this.setState({
                            loading: false
                        })
                        message.error("头像上传错误：" + info.file.response.msg);
                    }
                }

            );
        }

    };
    /**
     * 上传附件
     */
    handleUpload = () => {
        const { fileList } = this.state;
        const formData = new FormData();
        this.setState({
            uploading: true,
          });
        fileList.forEach(file => {
          formData.append('file', file);
          formData.append('resumeId',this.props.resumeId);
          const isLt2M = file.size / 100 / 1024 < 3;

            if (!isLt2M) {
                message.error('请上传小于300kb的文件!');
            }
            else{
                let headers=getTokenHeader({});
                reqwest({
                    url: `${baseUrl}file/prizeFile.do`,
                    method: 'post',
                    processData: false,
                    data: formData,
                    headers:headers,
                    success: (data) => {
                       message.success('上传成功.');
                       this.getInforList();
    
                    },
                    error: () => {
                      this.setState({
        
                        uploading: false,
                      });
                      message.error('上传失败.');
                    },
                  });
            }
          
        });
       
        this.setState({
            fileList:[],
            uploading: false,
          });
    

       
      };
    /**
     * 提交修改
     */
    handleSubmit=()=>{
        let data = this.props.form.getFieldsValue();
        data.avatar=this.state.imageUrl;
        data.id=this.state.resumeId;
        this.props.dispatch(changeInfo(data));
    }
   

    next=()=> {
        const current = this.state.current + 1;
        this.setState({ current });
      }
    
      prev=()=> {
        const current = this.state.current - 1;
        this.setState({ current });
      }
    render(){
        const {getFieldDecorator}=this.props.form;
        const {imageUrl,uploading, fileList,current} =this.state;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        const uploadButton = (
            <div>
                <Icon type={this.state.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">请上传jpg或png格式并小于300kb的个人照片</div>
            </div>
        );
        const props = {
            onRemove: file => {
              this.setState(state => {
                const index = state.fileList.indexOf(file);
                const newFileList = state.fileList.slice();
                newFileList.splice(index, 1);
                return {
                  fileList: newFileList,
                };
              });
            },
            beforeUpload: file => {
              this.setState(state => ({
                fileList: [...state.fileList, file],
              }));
              return false;
            },
            fileList,
          };
          const steps = [
            {
              title: '报名信息审核',
              content: <div className="stepBox">
                  <h2>审核结果：{this.state.stepInfor[0].status==0?<span style={{color:"red"}}><Icon type="close" />拒绝</span>:this.state.stepInfor[0].status==1?<span style={{color:"green"}}><Icon type="check" />通过</span>:<span style={{color:"#222222"}}>等待审核</span>}</h2>
            <div>审核人：<span>{this.state.stepInfor[0].examineUser==null?'正在审核中...':this.state.stepInfor[0].examineUser}</span></div>
                  <div>审核时间：<span>{this.state.stepInfor[0].examineTime==null?'正在审核中...':timeFormat(this.state.stepInfor[0].examineTime)}</span></div>
                  <div>审核意见：<span>{this.state.stepInfor[0].examineSuggestion==null?'正在审核中...':this.state.stepInfor[0].examineSuggestion}</span></div>
              </div>,
            },
            {
              title: '机考',
              content: <div className="stepBox">
                  <h2>审核结果：{this.state.stepInfor[1].status==0?<span style={{color:"red"}}><Icon type="close" />拒绝</span>:this.state.stepInfor[1].status==1?<span style={{color:"green"}}><Icon type="check" />通过</span>:<span style={{color:"#222222"}}>等待审核</span>}</h2>
              <div>审核人：<span>{this.state.stepInfor[1].examineUser==null?'正在审核中...':this.state.stepInfor[1].examineUser}</span></div>
                  <div>审核时间：<span>{this.state.stepInfor[1].examineTime==null?'正在审核中...':timeFormat(this.state.stepInfor[1].examineTime)}</span></div>
                  <div>审核意见：<span>{this.state.stepInfor[1].examineSuggestion==null?'正在审核中...':this.state.stepInfor[1].examineSuggestion}</span></div>
                  <br />
                  <br />
                  <br />
                  {
                      this.state.file1.length>0?<> <div>成绩文件：</div>
                      {
                          this.state.file1.map((item,index)=>{
                              return <div key={index} onClick={()=>this.getFile(item.id)}>
                                  <a href={`${baseUrl}file/downloadScore.do?id=`+item.id} target="_blank"><Icon type="download" />{item.name}</a>
                                  </div>
                          })
                      }</>:''
                  }
                  
                  
          </div>,
            },
            {
              title: '面试',
              content:  <div className="stepBox">
                  <h2>审核结果：{this.state.stepInfor[2].status==0?<span style={{color:"red"}}><Icon type="close" />拒绝</span>:this.state.stepInfor[2].status==1?<span style={{color:"green"}}><Icon type="check" />通过</span>:<span style={{color:"#222222"}}>等待审核</span>}</h2>
              <div>审核人：<span>{this.state.stepInfor[2].examineUser==null?'正在审核中...':this.state.stepInfor[2].examineUser}</span></div>
                  <div>审核时间：<span>{this.state.stepInfor[2].examineTime==null?'正在审核中...':timeFormat(this.state.stepInfor[2].examineTime)}</span></div>
                  <div>审核意见：<span>{this.state.stepInfor[2].examineSuggestion==null?'正在审核中...':this.state.stepInfor[2].examineSuggestion}</span></div>
                  <br />
                  <br />
                  <br />
                  {
                      this.state.file2.length>0?<> <div>成绩文件：</div>
                                                {
                                                    this.state.file2.map((item,index)=>{
                                                        return <div key={index} >
                                                            <a href={`${baseUrl}file/downloadScore.do?id=`+item.id}><Icon type="download" />{item.name}</a>
                                                            </div>
                                                    })
                                                }</>:''
                  }
                 
            </div>,
            },
          ];
        
        return(
            <div>
                <Card>
                <Menu onClick={this.handleClick} selectedKeys={[this.state.currentMenu]} mode="horizontal">
                    <Menu.Item key="mail">
                    <Icon type="file" />
                    报名信息
                    </Menu.Item>
                    <Menu.Item key="app">
                    <Icon type="smile" />
                    招新进度
                    </Menu.Item>
                </Menu>
                {
                    this.state.currentMenu==='mail'?<div>
                        <Form layout='horizontal'>
                        <Row>
                            <Col span={9}>
                                <FormItem label="姓名" {...formItemLayout}>
                                    {
                                        getFieldDecorator('name',{
                                            initialValue:this.state.infor.name,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请填写您的姓名',
                                                },
                                                {
                                                    min: 2,
                                                    message: '姓名至少为 2 个字符',
                                                },
                                                {
                                                    max: 20,
                                                    message: '姓名至多为 15 个字符',
                                                },]
                                        })(<Input />)
                                    }
                                    </FormItem>
                                    <FormItem label="学号" {...formItemLayout}>
                                        {
                                            getFieldDecorator('stuNum',{
                                                initialValue:this.state.infor.stuNum,
                                                rules:[{
                                                    required: true,
                                                    message: '请填写您的学号',
                                                }]
                                            })(<Input />)
                                        }
                                    </FormItem>
                                    <FormItem label="性别" {...formItemLayout}>
                                        {
                                            getFieldDecorator('sex',{
                                                initialValue:this.state.infor.sex,
                                                rules:[{
                                                    required: true,
                                                    message: '请选择您的性别',
                                                }]
                                            })(<Radio.Group>
                                                <Radio value={1}>男</Radio>
                                                <Radio value={2}>女</Radio>
                                            </Radio.Group>)
                                        }
                                    </FormItem>
                                    <FormItem label="邮箱" {...formItemLayout}>
                                        {
                                            getFieldDecorator('email',{
                                                initialValue:this.state.infor.email,
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '请填写您的邮箱',
                                                    },
                                                    {
                                                        pattern: '^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$',
                                                        message: '请输入正确格式的邮箱号',
                                                    },]
                                            })(<Input />)
                                        }
                                    </FormItem>
                            </Col>
                            <Col span={9}>
                                <FormItem label="手机号码" {...formItemLayout}>
                                    {
                                        getFieldDecorator('phone',{
                                            initialValue:this.state.infor.phone,
                                            rules:[{
                                                required: true,
                                                message: '请填写您的手机号',
                                            }, {
                                                pattern: '^[1][3|4|5|6|7|8|9][0-9]{9}$',
                                                message: '请输入正确的手机号格式。',
                                            },]
                                        })(<Input />)
                                    }
                                </FormItem>
                                <FormItem label="班级" {...formItemLayout}>
                                    {
                                        getFieldDecorator('majorClass',{
                                            initialValue:this.state.infor.majorClass,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请填写您的班级',
                                                }]
                                        })(<Input />)
                                    }
                                </FormItem>
                                <FormItem label="学院" {...formItemLayout}>
                                    {
                                        getFieldDecorator('institution',{
                                            initialValue:this.state.infor.institution,
                                            rules:[{
                                                required: true,
                                                message: '请选择您的学院',
                                            }]

                                        })(<Select >
                                        <Option value="计算机科学与技术学院">计算机科学与技术学院</Option>
                                        <Option value="材料科学与工程学院">材料科学与工程学院</Option>
                                        <Option value="土木工程与建筑学院">土木工程与建筑学院</Option>
                                        <Option value="信息工程学院">信息工程学院</Option>
                                        <Option value="理学院">理学院</Option>
                                        <Option value="法学院">法学院</Option>
                                        <Option value="外国语学院">外国语学院</Option>
                                        <Option value="体育学科部">体育学科部</Option>
                                        <Option value="环境与资源学院">环境与资源学院</Option>
                                        <Option value="制造科学与工程学院">制造科学与工程学院</Option>
                                        <Option value="生命科学与工程/农学院">生命科学与工程/农学院</Option>
                                        <Option value="国防科技学院">国防科技学院</Option>
                                        <Option value="经济管理学院">经济管理学院</Option>
                                        <Option value="文学与艺术学院">文学与艺术学院</Option>
                                        <Option value="马克思主义学院">马克思主义学院</Option>
                                        <Option value="应用技术学院">应用技术学院</Option>

                                    </Select>)
                                    }
                                    </FormItem>
                                    <FormItem label="志愿班级" {...formItemLayout}>
                                        {
                                            getFieldDecorator('willingClass',{
                                                initialValue:this.state.infor.willingClass,
                                                rules:[{
                                                    required: true,
                                                    message: '请选择您志愿的班级',
                                                }]
                                            })(<Select style={{ width: 120 }}>
                                            {
                                                
                                                this.state.classes.map((item,index)=>{
                                                return <Option key={index} value={item}>{item}</Option>
                                                })
                                            }
                                            </Select>)
                                        }
                                    
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="照片" >
                                {getFieldDecorator('avatar', {
                                    initialValue:'',
                                    rules:[{
                                        required: true,
                                        message: '请上传头像',
                                    }]
                                })(
                                    <Upload
                                        name="file"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        showUploadList={false}
                                        action={`${baseUrl}file/avatar.do`}
                                        onChange={this.handleChange}
                                        headers={getTokenHeader({})}
                                        beforeUpload={this.beforeUpload}
                                    >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                    </Upload>
                                )}
                            </FormItem>
                            </Col>
                        </Row>
                        <Row >
                            <Col span={6}>
                                <FormItem label="第一学期高数成绩：">
                                    {
                                        getFieldDecorator('mathScore',{
                                            initialValue:this.state.infor.mathScore,
                                            rules:[{
                                                required: true,
                                                message: '请填写您第一学期高数成绩',
                                            }, {
                                                pattern: '^(0|[1-9][0-9]?|100)$',
                                                message: '请输入0~100的整数。',
                                            }]
                                        })(<Input style={{ width: 120 }} />)
                                    }
                                </FormItem>   
                            </Col>
                            <Col span={6}>
                                <FormItem label="第一学期英语分数：">
                                {
                                    getFieldDecorator('englishScore',{
                                        initialValue:this.state.infor.englishScore,
                                        rules:[{
                                            required: true,
                                            message: '请填写您第一学期英语分数',
                                        }, {
                                            pattern: '^(0|[1-9][0-9]?|100)$',
                                            message: '请输入0~100的整数。',
                                        }]
                                    })(<Input style={{ width: 120 }} />)
                                }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="PAT成绩(例如：甲级70分 or 乙级70分)：">
                                    {
                                        getFieldDecorator('patScore',{
                                            initialValue:this.state.infor.patScore,
                                        })(<Input style={{ width: 120 }} />)
                                    }
                                </FormItem>
                            </Col>
                            <Col span={5}>
                            <FormItem label="CSP成绩：">
                                {
                                    getFieldDecorator('ccfScore',{
                                        initialValue:this.state.infor.ccfScore,
                                        rules:[{
                                            pattern: '^[0-9]*$',
                                            message: '请输入数字。',
                                        }]
                                    })(<Input style={{ width: 120 }} />)
                                }
                            </FormItem>
                            </Col>
                        </Row>
                        <Row>
                        <FormItem label="申请原因：" >
                            {
                                getFieldDecorator('applyReason',{
                                    initialValue:this.state.infor.applyReason,
                                    rules:[{
                                        required: true,
                                        message: '请填写您的申请原因',
                                    }]
                                })( <TextArea placeholder="" style={{width:'50vw'}}  autoSize={{ minRows: 2, maxRows: 6 }} /> )
                            }
                        </FormItem>
                        <FormItem label="获奖经历：" >
                            {
                                getFieldDecorator('prizeExperience',{
                                    initialValue:this.state.infor.prizeExperience,
                                    rules:[{
                                        required: true,
                                        message: '请填写您的获奖经历',
                                    }]
                                })( <TextArea placeholder="获奖经历分点列出" style={{width:'50vw'}} autoSize={{ minRows: 2, maxRows: 6 }} /> )
                            }
                        </FormItem>
                        </Row>
                        <Button type="primary" onClick={this.handleSubmit}>提交修改</Button>
                        </Form>
                        <br></br>
                        <br></br>
                        <br></br>
                        <div className="userHome-upLoad">
                            <ul>
                            {
                                this.state.list.map((item)=>{
                                    return <li key={item.id}>
                                            <span><a href={item.url} target="_blank">{item.name}</a></span><span style={{marginLeft:100}} onClick={()=>this.deleteList(item.id)}><a><Icon type="delete" /></a></span>
                                    </li>
                                })
                            }
                            </ul>
                            <div>上传附件（文件大小不超过300kb）：</div>
                            <br></br>
                            <Upload {...props}>
                                <Button>
                                    <Icon type="upload" />选择文件
                                </Button>
                            </Upload>
                            <Button
                                type="primary"
                                onClick={this.handleUpload}
                                disabled={fileList.length === 0}
                                loading={uploading}
                                style={{ marginTop: 16 }}
                                >
                                {uploading ? '上传中' : '开始上传'}
                            </Button>
                        </div>
                    </div>:<div className="userHome-steps">
                    <Steps current={current}>
          {steps.map(item => (
            <Step key={item.title} title={item.title} />
          ))}
        </Steps>
        <div className="steps-content">{steps[current].content}</div>
        <div className="steps-action">
          {current < this.state.stepLen-1 && (
            <Button type="primary" onClick={() => this.next()}>
              下一阶段
            </Button>
          )}
          {current === this.state.stepLen-1 && (
            <Button type="primary" onClick={() => message.success('已经是最后阶段了!')}>
              完成
            </Button>
          )}
          {current > 0 && (
            <Button style={{ marginLeft: 8 }} onClick={() => this.prev()}>
              上一个阶段
            </Button>
          )}
        </div>
                    </div>
                }
                </Card>
            </div>
        )
    }
}
export default Form.create()(UserHome);